<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

/**
 * 权限
 */
class PermissionController extends CommonController
{

    public $model = null;
    public function __construct()
    {
        parent::__construct();

        $this->model = new \App\Models\Permission();
    }


    /**
     * 权限树形列表 （可用于筛选）
     * @param type 0 或空获取全部数据  1 获取一级菜单  2 获取一级菜单下的所有子菜单  3 获取全部数据，但是只返回 id 和 权限名称（主要用于筛选）
     * @param pid 当type 为 2时，必填  一次菜单的id 
     */
    public function permissionTree()
    {
        $type = $this->request->input('type', 0);
        $pid = $this->request->input('pid', 0);
        if ($type == 2 && empty($pid)) {
            return $this->returnApi(201, '一级子菜单id不能为空');
        }

        $res = $this->model->gerPermissionList($this->request->manage_id, $type, $pid);

        return $this->returnApi(200, '获取成功', true, $res);
    }

    /**
     * 列表
     * @param page int 当前页
     * @param limit int 分页大小
     * @param type string 类型  0、全部 1、目录  2、菜单 3、页面   4、按钮
     * @param keywords string 搜索关键词
     * @param keywords_type string 类型  0、全部  permission_name、权限名称   pid、父级id   route_name、路由别名   api_path、api路径   view_name、命名视图
     */
    public function permissionList()
    {
        //echo phpinfo();die;
        $page = request()->page ? intval(request()->page) : 1;
        $limit = request()->limit ? intval(request()->limit) : 10;
        $keywords = request()->keywords;
        $keywords_type = request()->keywords_type;
        $type = request()->type;

        $permission_ids = $this->model->getUserPermissionId($this->request->manage_id);

        $res = $this->model
            ->whereIn('id', $permission_ids)
            ->where(function ($query) use ($type) {
                if ($type) {
                    $query->where('type', $type);
                }
            })->where(function ($query) use ($keywords_type, $keywords) {
                if (!empty($keywords)) {
                    if (empty($keywords_type)) {
                        $query->orWhere('permission_name', 'like', "%$keywords%")
                            ->orWhere('pid', 'like', "%$keywords%")
                            ->orWhere('route_name', 'like', "%$keywords%")
                            ->orWhere('api_path', 'like', "%$keywords%")
                            ->orWhere('view_name', 'like', "%$keywords%");
                    } elseif ($keywords_type == 'permission_name') {
                        $query->where('permission_name', 'like', "%$keywords%");
                    } elseif ($keywords_type == 'pid') {
                        $query->where('pid', 'like', "%$keywords%");
                    } elseif ($keywords_type == 'route_name') {
                        $query->where('route_name', 'like', "%$keywords%");
                    } elseif ($keywords_type == 'api_path') {
                        $query->where('api_path', 'like', "%$keywords%");
                    } elseif ($keywords_type == 'view_name') {
                        $query->where('view_name', 'like', "%$keywords%");
                    }
                }
            })->where('is_del', 1)
            ->orderBy('order')
            ->paginate($limit)
            ->toArray();

        if ($res['data']) {
            $res = $this->disPageData($res);
            //增加序号
            $res['data'] = $this->addSerialNumber($res['data'], $page, $limit);

            return $this->returnApi(200, '获取成功', true, $res);
        }

        return $this->returnApi(203, '暂无数据');
    }

    /**
     * 详情
     * @param id int 权限id
     */
    public function permissionDetail()
    {
        $id = request()->id;

        if (!$id) {
            return $this->returnApi(201, '参数传递错误');
        }

        $permission_ids = $this->model->getUserPermissionId($this->request->manage_id);
        if (!in_array($id, $permission_ids)) {
            return $this->returnApi(202, '您无权限查看此信息');
        }

        $res = $this->model->find($id);


        if (!$res) {
            return $this->returnApi(201, '参数传递错误');
        }

        return $this->returnApi(200, 'ok', true, $res->toArray());
    }


    /**
     * 新增
     * @param permission_name string 权限名称
     * @param type int 权限类型 1目录 2菜单 3页面 4按钮   改为  1 菜单  2 页面  3按钮
     * //@param sidebar_name string 侧边栏名称 目录与菜单必填
     * @param icon string 图标 侧边栏必填
     * @param route_name string 路由名称 
     * @param meta_title string 页面标题
     * @param route_path string 路由路径 菜单,页面必填
     * @param component_path string 选填
     * @param pid id 父级id 菜单，页面，按钮必填
     * @param api_path string 权限包含接口   多个 逗号 拼接    除菜单外必填
     * @param order number 排序  数字越小  越靠前  1在最前面
     * @param view_name string 命名识图名称
     * //@param redirect string 重定向地址
     * //@param hl_routes string 高亮路由定义
     * @param is_admin 是否为admin管理员独有权限  1是 2不是   默认2
     * 
       侧边栏必须填写 type = 1 sidebar_name permission_name  icon route_name 
       菜单必须填写 type = 2 sidebar_name permission_name  route_name route_path component_path pid 
       页面必须填写 type = 3 permission_name  route_name route_path component_path pid api_path
       按钮必须填写 type = 4 permission_name pid api_path
     */
    public function permissionInsert()
    {
        // $validate = new \app\api\validate\PermissionValidate();
        // if (!$validate->scene('insert')->check(request()->param())) {
        //     return $this->returnApi(201, $validate->getError());
        // }
        $permission_name = request()->permission_name ? request()->permission_name : null;
        $type = request()->type ? request()->type : null;
        // $icon = request()->icon ? request()->icon : null;
        //$sidebar_name = request()->sidebar_name ? request()->sidebar_name : null;
        //   $route_name = request()->route_name ? request()->route_name : null;
        $route_path = request()->route_path ? request()->route_path : null;
        //  $component_path = request()->component_path ? request()->component_path : null;
        $pid = request()->pid ? request()->pid : null;
        $api_path = request()->api_path ? request()->api_path : null;
        $meta_title = request()->meta_title;

        //只能是超级管理员才能添加
        if (request()->manage_id != 1) {
            return $this->returnApi(202, '您无权限添加此数据');
        }


        if (empty($permission_name)) {
            return $this->returnApi(202, '权限名称不能为空');
        }
        if (($type == 1 && $type == 2) && empty($meta_title)) {
            return $this->returnApi(202, '页面标题不能为空');
        }

        $is_exists = $this->model->permissionIsExists($permission_name, null, $type, $route_path);
        if ($is_exists) {
            return $this->returnApi(202, '此权限名称已存在，请重新添加');
        }

        // if (($type == 1 || $type == 2) && !$sidebar_name) {
        //     return $this->returnApi(202, '请填写路由侧边栏名称');
        // }
        // if(($type == 1) && !$icon){
        //     return $this->returnApi(202, '请填写目录图标类名称');
        // }
        // if (($type == 2 || $type == 3)  && !$route_name) {
        //     return $this->returnApi(202, '请填写路由名称');
        // }
        // if (($type == 3)  && !$meta_title) {
        //     return $this->returnApi(202, '请填写页面名称');
        // }
        if ($type == 2 && !$route_path) {
            return $this->returnApi(202, '请填写路由路径');
        }
        if (($type != 1 && $type != 2 && $type != 3) && !$pid) {
            return $this->returnApi(202, '请选择父级目录');
        }
        if (($type == 2 || $type == 3) && !$api_path) {
            return $this->returnApi(202, '请填写权限对应的接口路由');
        }

        DB::beginTransaction();
        try {

            $this->model->add($this->request);

            DB::commit();
            return $this->returnApi(200, '新增成功', true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, '新增失败');
        }
    }


    /**
     * 编辑
     * @param id int 权限id
     * @param permission_name string 权限名称
     * @param type int 权限类型 1目录 2菜单 3页面 4按钮   改为  1 菜单  2 页面  3按钮
     * //@param sidebar_name string 侧边栏名称 目录与菜单必填
     * @param icon string 图标 侧边栏必填
     * @param route_name string 路由名称 
     * @param meta_title string 页面标题
     * @param route_path string 路由路径  除菜单外必填
     * @param component_path string 选填
     * @param pid id 父级id 菜单，页面，按钮必填
     * @param api_path string 权限包含接口  多个 逗号 拼接  除菜单外必填
     * @param order number 排序
     * @param view_name string 命名识图名称
     * //@param redirect string 重定向地址
     * //@param hl_routes string 高亮路由定义
     * @param is_admin 是否为admin管理员独有权限  1是 2不是  默认2
     */
    public function permissionChange()
    {

        // $validate = new \app\api\validate\PermissionValidate();
        // if (!$validate->scene('update')->check(request()->param())) {
        //     return $this->returnApi(201, $validate->getError());
        // }

        //只能是超级管理员才能添加
        if (request()->manage_id != 1) {
            return $this->returnApi(202, '您无权限修改此数据');
        }

        $id = request()->id;

        if (!$id) {
            return $this->returnApi(201, '参数传递错误');
        }
        $permission = $this->model->find($id);

        if (!$permission) {
            return $this->returnApi(201, '参数传递错误');
        }

        $permission_name = request()->permission_name ? request()->permission_name : null;
        $type = request()->type ? request()->type : null;
        // $sidebar_name = request()->sidebar_name ? request()->sidebar_name : null;
        //   $icon = request()->icon ? request()->icon : null;
        //  $route_name = request()->route_name ? request()->route_name : null;
        $route_path = request()->route_path ? request()->route_path : null;
        //  $component_path = request()->component_path ? request()->component_path : null;
        $pid = request()->pid ? request()->pid : null;
        $api_path = request()->api_path ? request()->api_path : null;
        $meta_title = request()->meta_title;


        if (empty($permission_name)) {
            return $this->returnApi(202, '权限名称不能为空');
        }

        if (($type == 1 && $type == 2) && empty($meta_title)) {
            return $this->returnApi(202, '页面标题不能为空');
        }

        $is_exists = $this->model->permissionIsExists($permission_name, $id, $type, $route_path);
        if ($is_exists) {
            return $this->returnApi(202, '此权限名称已存在，请重新添加');
        }

        /*  if (($type == 1 || $type == 2) && !$sidebar_name) {
            return $this->returnApi(202, '请填写路由侧边栏名称');
        } */
        // if (($type == 1) && !$icon) {
        //     return $this->returnApi(202, '请填写目录图标类名称');
        // }
        // if (($type == 2 || $type == 3)  && !$route_name) {
        //     return $this->returnApi(202, '请填写路由名称');
        // }


        if ($type == 2 && !$route_path) {
            return $this->returnApi(202, '请填写路由路径');
        }
        if (($type != 1 && $type != 5) && !$pid) {
            return $this->returnApi(202, '请选择父级目录');
        }
        if (($type == 2 || $type == 3) && !$api_path) {
            return $this->returnApi(202, '请填写权限对应的接口路由');
        }

        DB::beginTransaction();
        try {
            $this->model->change($this->request);

            DB::commit();
            return $this->returnApi(200, '编辑成功', true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, '编辑失败');
        }
    }


    /**
     * 删除
     * @param id int 权限id
     */
    public function permissionDel()
    {
        //只能是超级管理员才能添加
        if (request()->manage_id != 1) {
            return $this->returnApi(202, '您无权限删除此数据');
        }

        $id = request()->id;

        if (!$id) {
            return $this->returnApi(201, '参数传递错误');
        }

        $permission = $this->model->find($id);

        if (!$permission) {
            return $this->returnApi(201, '参数传递错误');
        }

        $permission->is_del = "2";
        $res = $permission->save();

        if (!$res) {
            return $this->returnApi(202, '删除失败');
        }

        return $this->returnApi(200, '删除成功', true);
    }

    /**
     * 更改权限排序
     * @param orders 排序   json格式数据  里面2个参数  id 权限id   order 序号
     * 
     * json 格式数据  [{"id":1,"order":1},{"id":2,"order":2},{"id":3,"order":3}]
     * 数组 格式数据  [['id'=>1 , 'order'=>1] , ['id'=>2 , 'order'=>2] , ['id'=>3 , 'order'=>3]]
     */
    public function permissionOrderChange()
    {
        //只能是超级管理员才能添加
        if (request()->manage_id != 1) {
            return $this->returnApi(202, '您无权限编辑此数据');
        }

        $orders = request()->orders;
        if (empty($orders)) {
            return $this->returnApi(201, '参数错误');
        }
        $orders = json_decode($orders, true);

        DB::beginTransaction();
        try {
            foreach ($orders as $key => $value) {
                $this->model->where('id', $value['id'])->update(['order' => $value['order']]);
            }
            DB::commit();
            return $this->returnApi(200, '修改成功', true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, '修改失败');
        }
    }
}
